package com.geeklan.smart.ui.pet;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.base.utils.ActivityUtil;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.PetInfo;
import com.geeklan.smart.data.remote.oss.AsyncMultiFileUploader;
import com.geeklan.smart.data.remote.oss.FileUploader;
import com.geeklan.smart.data.remote.oss.UploadCallback;
import com.geeklan.smart.data.remote.oss.UploadMultifileCallback;
import com.geeklan.smart.data.repository.device.DeviceRepository;
import com.geeklan.smart.data.repository.pet.PetRepository;
import com.geeklan.smart.databinding.ActivityAddPetInfoBinding;
import com.geeklan.smart.ui.dialog.DateBottomSheetDialog;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModel;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModelFactory;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModel;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModelFactory;
import com.geeklan.smart.utils.ImagePathUtils;
import com.geeklan.smart.utils.ListUtils;

import java.util.ArrayList;

public class AddPetInfoActivity extends BaseActivity<ActivityAddPetInfoBinding> implements View.OnClickListener {
    private ArrayList<String> photoPaths = new ArrayList<>();
    private int petType = 1;
    private String typeName;
    private String headUri;
    private String etPetName;
    private int petSex = 1;
    private float petWeight = 0;
    private String brithday;
    private String headUrl;
    private ArrayList<String> photoUrls = new ArrayList<>();
    private PetViewModel petViewModel;

    @Override
    protected ActivityAddPetInfoBinding initBinding() {
        return ActivityAddPetInfoBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        photoPaths = getIntent().getStringArrayListExtra("photoPaths");
        petType = getIntent().getIntExtra("petType", 1);
        typeName = getIntent().getStringExtra("typeName");
        headUri = getIntent().getStringExtra("headUri");
        etPetName = getIntent().getStringExtra("petName");

        petViewModel = new ViewModelProvider(this, new PetViewModelFactory(new PetRepository())).get(PetViewModel.class);

        petViewModel.getAddPetLiveData().observe(this, response -> {
            dismiss();
            Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
            finish();
            ActivityUtil.getInstance().finishActivity(SelectPetActivity.class);
            ActivityUtil.getInstance().finishActivity(AddPetActivity.class);
        });

        petViewModel.getAddPetErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.includeSex.llGG.setOnClickListener(this);
        mBinding.includeSex.llGGNotJJ.setOnClickListener(this);
        mBinding.includeSex.llMM.setOnClickListener(this);
        mBinding.includeSex.llMMNeuter.setOnClickListener(this);
        mBinding.tvBirthday.setOnClickListener(this);
        mBinding.tvSubmit.setOnClickListener(this);
        sexSelected(0);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == mBinding.includeSex.llGG.getId()) {
            petSex = 1;
            sexSelected(0);
        } else if (id == mBinding.includeSex.llGGNotJJ.getId()) {
            petSex = 3;
            sexSelected(1);
        } else if (id == mBinding.includeSex.llMM.getId()) {
            petSex = 2;
            sexSelected(2);
        } else if (id == mBinding.includeSex.llMMNeuter.getId()) {
            petSex = 4;
            sexSelected(3);
        } else if (id == mBinding.tvBirthday.getId()) {
            DateBottomSheetDialog dateBottomSheetDialog = new DateBottomSheetDialog(this);
            dateBottomSheetDialog.setCancelableOutside(true); // 点击背景关闭
            dateBottomSheetDialog.setOnDateSelectedListener((year, month, day) -> {
                brithday = year + "-" + month + "-" + day;
                mBinding.tvBirthday.setText(brithday);
            });
            dateBottomSheetDialog.show();
        } else if (id == mBinding.tvSubmit.getId()){
            if(TextUtils.isEmpty(brithday)) {
                Toast.makeText(this,"请选择生日",Toast.LENGTH_SHORT).show();
                return;
            }
            petWeight = mBinding.includeWeight.horizontalRuler.getSelectedValue();

            if(petWeight <= 0) {
                Toast.makeText(this,"请选择体重",Toast.LENGTH_SHORT).show();
                return;
            }

            loading();

            FileUploader.uploadFile(this, headUri, new UploadCallback() {
                @Override
                public void onUploadSuccess(String fileUrl) {
                    AddPetInfoActivity.this.headUrl = fileUrl;
                    checkUploadComplete();
                }
                @Override
                public void onUploadFailure() {
                    dismiss();
                    Toast.makeText(AddPetInfoActivity.this,"头像上传失败",Toast.LENGTH_SHORT).show();
                }
            });
            AsyncMultiFileUploader.uploadFiles(this, photoPaths, new UploadMultifileCallback() {
                @Override
                public void onUploadSuccess(String fileName) {
                    photoUrls.add(fileName);
                }

                @Override
                public void onUploadFailure(String fileName, String error) {
                    handler.sendEmptyMessage(2);
                }

                @Override
                public void onAllUploadsComplete(int successCount, int failureCount) {
                    checkUploadComplete();
                }
            });
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if(msg.what == 0){
                loading();
            } else if (msg.what == 1) {
                dismiss();
                Toast.makeText(AddPetInfoActivity.this, "照片上传失败", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

    private void checkUploadComplete(){
        boolean isComplete = true;
        if(headUrl == null || headUrl.isEmpty()){
            isComplete = false;
        }
        if(photoUrls.size() != photoPaths.size()){
            isComplete = false;
        }

        if(isComplete){
            dismiss();
            PetInfo petInfo = new PetInfo();
            petInfo.setBirthday(brithday);
            petInfo.setPetType(petType);
            petInfo.setName(etPetName);
            petInfo.setPic(headUrl);
            petInfo.setSex(petSex);
            petInfo.setWeight(String.format("%.1f", petWeight));
            petInfo.setVariety(typeName);
            petInfo.setPetAlbum(ListUtils.convertArrayListToFormattedString(photoUrls));
            petViewModel.addPet(petInfo);
        }
    }

    private void sexSelected(int index) {
        if (index == 0) {
            mBinding.includeSex.llGG.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_2773ff_radius_5_bg));
            mBinding.includeSex.llGGNotJJ.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llMM.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llMMNeuter.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.ivGG.setImageResource(R.drawable.ic_gg);
            mBinding.includeSex.ivGGNotJJ.setImageResource(R.drawable.ic_gg_def);
            mBinding.includeSex.ivMM.setImageResource(R.drawable.ic_mm_def);
            mBinding.includeSex.ivMMNeuter.setImageResource(R.drawable.ic_mm_def);
            mBinding.includeSex.tvGG.setTextColor(getColor(R.color.color_2773FF));
            mBinding.includeSex.tvGGNotJJ.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvMM.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvMMNeuter.setTextColor(getColor(R.color.color_999999));
        } else if (index == 1) {
            mBinding.includeSex.llGG.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llGGNotJJ.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_2773ff_radius_5_bg));
            mBinding.includeSex.llMM.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llMMNeuter.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.ivGG.setImageResource(R.drawable.ic_gg_def);
            mBinding.includeSex.ivGGNotJJ.setImageResource(R.drawable.ic_gg);
            mBinding.includeSex.ivMM.setImageResource(R.drawable.ic_mm_def);
            mBinding.includeSex.ivMMNeuter.setImageResource(R.drawable.ic_mm_def);
            mBinding.includeSex.tvGG.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvGGNotJJ.setTextColor(getColor(R.color.color_2773FF));
            mBinding.includeSex.tvMM.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvMMNeuter.setTextColor(getColor(R.color.color_999999));
        } else if (index == 2) {
            mBinding.includeSex.llGG.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llGGNotJJ.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llMM.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_ff378c_radius_5_bg));
            mBinding.includeSex.llMMNeuter.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.ivGG.setImageResource(R.drawable.ic_gg_def);
            mBinding.includeSex.ivGGNotJJ.setImageResource(R.drawable.ic_gg_def);
            mBinding.includeSex.ivMM.setImageResource(R.drawable.ic_mm);
            mBinding.includeSex.ivMMNeuter.setImageResource(R.drawable.ic_mm_def);
            mBinding.includeSex.tvGG.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvGGNotJJ.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvMM.setTextColor(getColor(R.color.color_ff378c));
            mBinding.includeSex.tvMMNeuter.setTextColor(getColor(R.color.color_999999));
        } else if (index == 3) {
            mBinding.includeSex.llGG.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llGGNotJJ.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llMM.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_f5_radius_5_bg));
            mBinding.includeSex.llMMNeuter.setBackground(AppCompatResources.getDrawable(this, R.drawable.layout_ff378c_radius_5_bg));
            mBinding.includeSex.ivGG.setImageResource(R.drawable.ic_gg_def);
            mBinding.includeSex.ivGGNotJJ.setImageResource(R.drawable.ic_gg_def);
            mBinding.includeSex.ivMM.setImageResource(R.drawable.ic_mm_def);
            mBinding.includeSex.ivMMNeuter.setImageResource(R.drawable.ic_mm);
            mBinding.includeSex.tvGG.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvGGNotJJ.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvMM.setTextColor(getColor(R.color.color_999999));
            mBinding.includeSex.tvMMNeuter.setTextColor(getColor(R.color.color_ff378c));
        }
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context, ArrayList<String> pathList, String headUri, String etPetName, int petType, String typeName){
        Intent intent = new Intent(context, AddPetInfoActivity.class);
        intent.putStringArrayListExtra("photoPaths",pathList);
        intent.putExtra("headUri",headUri.toString());
        intent.putExtra("petName",etPetName);
        intent.putExtra("petType", petType);
        intent.putExtra("typeName", typeName);
        context.startActivity(intent);
    }
}